jsMotif.comm.jsonp = (function(){
    
    var _dom = jsMotif.dom,
        _seed = 100,
        _cbfnNS= 'jsMotif.comm.jsonp',
        _defaultTimeout = 4000;
  
    function getCbId(){
        return ++_seed;
    }
  
    function get (url) {      
        var script = _dom.create('script', {
            src: url,
            type: 'text/javascript'
        });     
                
        script.onload = function(){
            _dom.remove(this);
        };
        //ie hack
        script.onreadystatechange = function () {
            if (this.readyState === 'loaded') {
                _dom.remove(this);
            }
        };      
        _dom.append(document.body, script);        
    }
    
    function removeCallBack(cbName){
        delete jsMotif.comm.jsonp[cbName];
    }
    
    function createHandler (onComplete, timeout){
        var $comm = jsMotif.comm, 
            cbId = getCbId(),
            handlerName = 'handle' + cbId,
            timeoutHandler = setTimeout(function(){
                onComplete({}, 'timeout');
                $comm.jsonp[handlerName] = function(){};
                //add 5 sec and remove callback if request eventually will come in
                setTimeout(function(){
                    removeCallBack(handlerName);
                },5000);
                
            }, timeout || _defaultTimeout);
        
        $comm.jsonp[handlerName] = function (data) {
            clearTimeout(timeoutHandler);
            onComplete(data, 'ok');
            removeCallBack(handlerName);
        };
        
        return handlerName;
    }
    
    function getJson (url, onComplete, params) {
        var timeout = (params)? params.timeout : '',
            handlerName =  createHandler(onComplete, timeout),
            requestUrl = url.replace('{CB_FN}', [_cbfnNS , handlerName].join('.'));
       
        get(requestUrl);
    }
    
    
    return {
        getJson: getJson
    };
    
}());
